<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ObjectUtil } from '@utils/object-util'
import { ElForm, ElTable } from 'element-plus'
import { TableUtil } from '@utils/table-util'
import { MountedCheck } from '@/utils'
import { getSimCardListByPageAPI, simCardAlarmSettingsAPI } from '@/api/sim-card'
import { cIdStatusMap } from '@/dataset'
import { CardDTO } from '@/api/entity/sim-card'
import { InfoFilled } from '@element-plus/icons-vue'
import { delSelfShareInfoAPI, getSelfShareListByPageAPI, selfEditShareInfoAPI, selfShareByPhoneAPI } from '@/api/share'
import YkDatePicker from '@yk/components/date-picker/YkDatePicker.vue'
import { ConfigurationDTO, ConfigurationRoleDTO } from '@/api/entity/self-config'
import { phoneRule } from '@utils/form-rule'

const router = useRouter()
const route = useRoute()
defineOptions({ name: 'SimManage' })

const mc = new MountedCheck()
onMounted(() => {
  searchParams.configurationId = route.query.id as string
  searchHandle()
  mc.end()
})

onActivated(() => {
  if (mc.isMounted()) return
  getTableData()
})

// region TODO 查询
const searchParams = reactive({
  configurationId: '',
  // 共享状态（0代表不共享 1代表共享 2代表管理员）
  status: '',
  // 开始时间
  startTime: '',
  // 结束时间
  endTime: ''
})
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = shallowRef<ConfigurationRoleDTO[]>([])
const tableDataRef = ref<InstanceType<typeof ElTable>>()
function getTableData () {
  const loading = ElLoading.service()
  getSelfShareListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records
      pages.total = rdata.total
    })
  })
  loading.close()
}
function delTableItem (id: string) {
  ElMessageBox.confirm('删除当前记录？', '删除提醒').then(() => {
    delSelfShareInfoAPI({ id }).then((res) => {
      res.result().then(() => {
        getTableData()
      })
    })
  })
}
// endregion

// region TODO 导出
const exportParams = shallowRef<typeof searchParams>()
// endregion

// region TODO 取消分享
function unshare (id: string) {
  ElMessageBox.confirm('取消后对方将无法查看该组态，是否确定？', '取消分享').then(() => {
    const loading = ElLoading.service()
    selfEditShareInfoAPI({ id, status: '1' }).then(res => {
      res.result().then(() => {
        ElMessage.success('已取消')
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion

// region TODO 分享组态 - 修改
const shareDialogModel = ref(false)
const shareSelfFormRef = shallowRef<InstanceType<typeof ElForm>>()
const shareSelfForm = ref<Parameters<typeof selfEditShareInfoAPI>[0]>({
  id: '',
  expiredTime: ''
})

function showShareDialog (item: ConfigurationRoleDTO) {
  ObjectUtil.updateVal(shareSelfForm.value, item)
  shareDialogModel.value = true
}
function closeShareDialog () {
  if (!shareDialogModel.value) return
  shareDialogModel.value = false
  shareSelfFormRef.value.resetFields()
}
function submitShareSelfForm () {
  const loading = ElLoading.service()
  shareSelfFormRef.value.validate().then(() => {
    selfEditShareInfoAPI(shareSelfForm.value).then((res) => {
      res.result().then(() => {
        ElMessage.success('修改成功')
        getTableData()
        closeShareDialog()
      })
    })
  }).finally(loading.close)
}
// endregion

</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100 flex-1">
      <div class="c_card_header c_card-title bor-divider-b">组态分享列表</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-3" @submit.prevent="searchHandle">
        <el-form-item label="条件">
          <el-select v-model="searchParams.status" placeholder="全部状态" clearable>
            <el-option value="">全部</el-option>
            <el-option label="共享中" value="0" />
            <el-option label="已失效" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <yk-date-picker v-model:start="searchParams.startTime" v-model:end="searchParams.endTime" type="datetimerange" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
        <!--<el-form-item class="float-right mr-0">-->
        <!--  <el-button type="primary" plain @click="alarmConfig">报警配置</el-button>-->
        <!--</el-form-item>-->
      </el-form>
      <!--表格-->
      <el-table ref="tableDataRef" class="c_table-page w-100" stripe :data="tableData">
        <el-table-column type="selection" />
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(null, pages)" />
        <yk-table-column label="组态名称" prop="configurationName" />
        <yk-table-column label="分享账号" prop="phone" />
        <yk-table-column label="共享有效期" prop="expiredTime">
          <template #default="scope">{{ scope.row.expiredTime || '永久' }}</template>
        </yk-table-column>
        <yk-table-column label="共享时间" prop="createdAt" />
        <yk-table-column label="共享状态" prop="autoname">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '1'" type="danger" effect="light" size="small">已失效</el-tag>
            <el-tag v-else-if="scope.row.status === '0'" effect="light" size="small">共享中</el-tag>
          </template>
        </yk-table-column>
        <el-table-column label="操作" width="250px">
          <template #default="scope">
            <div class="c_table-operation">
              <el-link v-if="scope.row.status === '1'" type="danger" size="small" @click="delTableItem(scope.row.id)">删除记录</el-link>
              <template v-else>
                <el-link type="primary" size="small" @click="showShareDialog(scope.row)">修改</el-link>
                <el-link type="danger" size="small" @click="unshare(scope.row.id)">取消共享</el-link>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <!--分享组态-->
    <el-dialog
      v-model="shareDialogModel" title="分享组态" width="400px"
      :close-on-click-modal="false"
      @close="closeShareDialog"
    >
      <el-form
        ref="shareSelfFormRef"
        :model="shareSelfForm" style="margin: -20px 0;"
        label-width="100px"
        class="c_form-save"
      >
        <el-form-item label="共享有效期：" prop="expiredTime">
          <yk-date-picker
            v-model="shareSelfForm.expiredTime"
            type="datetime"
            optional-scope="after"
            placeholder="选择共享有效期"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <div class="d-flex justify-content-end w-100">
            <el-button type="primary" plain @click="closeShareDialog">取消</el-button>
            <el-button type="primary" @click="submitShareSelfForm()">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
